import React, {useState, useEffect, useRef } from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faSearch, faTimes } from '@fortawesome/free-solid-svg-icons'
import style from './FileSearch.module.css'
import PropTypes from 'prop-types'
import useKeyPress from '../../hooks/useKeyPress'

FileSearch.propTypes = {
  title: PropTypes.string,
  onFileSearch: PropTypes.func.isRequired
}

// 默认参数
FileSearch.defaultProps = {
  title: '我的云文档'
}

export default function FileSearch({title, onFileSearch}) {
  const [inputActive, setinputActive] = useState(false) // 搜索栏显示状态
  const [value, setValue] = useState('') // 搜索输入框内容
  const enterPressed = useKeyPress(13)
  const escPressed = useKeyPress(27)

  const node = useRef(null)

  // 输入框关闭
  const closeSearch = () => {
    setinputActive(false)
    setValue('')
    onFileSearch('')
  }

  useEffect(() => {
    if (enterPressed && inputActive) {
      onFileSearch(value)
    }
    if (escPressed && inputActive) {
      closeSearch()
    }
  })

  useEffect(() => {
    if (inputActive) {
      node.current.focus()
    }
  }, [inputActive])

  return (
    <div className={`alert alert-primary ${style.FileSearch} ${style['alert-main']} mb-0` }>
      {
        !inputActive && 
        <div className='d-flex justify-content-between align-items-center'>
          <span>{title}</span>
          <div
            className='icon-button'
            onClick={ () => setinputActive(true) }
          ><FontAwesomeIcon 
            title='搜索'
            icon={faSearch} 
          /></div>
        </div>
      }
      {
        inputActive && 
          <div className='d-flex justify-content-between align-items-center'>
            <input
            style={{width: "90%"}}
              value={value}
              onChange={ (e) => setValue(e.target.value) }
              ref={node}
            ></input>
            <div 
              onClick={ closeSearch }
            >
              <FontAwesomeIcon 
                title='关闭'
                icon={faTimes} 
              />
            </div>
          </div>
      }
    </div>
  )
}
